package com.zeei.gis.service.imp;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zeei.gis.dao.AreaCodeGisDao;
import com.zeei.gis.service.AreaCodeGisService;
import com.zeei.gis.vo.AreaCodeGisVO;

/**
 * @类型名称：AreaCodeGisServiceImpl
 * @类型描述：GIS一张图地区查询
 * @功能描述：GIS一张图地区查询
 * @创建人：jiangqingpeng
 */
@Service("areaCodeGisService")
public class AreaCodeGisServiceImpl implements AreaCodeGisService{

	@Autowired
	AreaCodeGisDao areaCodeGisDao;
 
	/**
	 * queryAreaCodeList：查询省市区信息
	 */
	@Override
	public AreaCodeGisVO queryAreaCodeGisList() {
		List<AreaCodeGisVO> areaCodeList = areaCodeGisDao.queryAreaCodeGisList();
		AreaCodeGisVO root = getRoot(areaCodeList);
		appendChilren(root);
		return root;
	}

	private void appendChilren(AreaCodeGisVO root) {
		AreaCodeGisVO parent = root;
		List<AreaCodeGisVO>  children = root.getChildren();
		List<AreaCodeGisVO> temps = null;
		
		if(children!=null && !children.isEmpty()){
			for(AreaCodeGisVO c : children) {
				if(c.getPcode().equals(parent.getCodeRegion())) {
					if(temps==null) {
						temps = new ArrayList<AreaCodeGisVO>();
					}
					temps.add(c);
					parent.setChildren(temps);
				}
			}
			
			if(temps!=null){
				children.removeAll(temps);
				for(AreaCodeGisVO c: temps) {
					c.setChildren(children);
					appendChilren(c);
				}
			}
		}
	}

	/**
	 * 查询省信息
	 * @param List<AreaCodeGisVO>
	 * @return AreaCodeGisVO
	 */
	private AreaCodeGisVO getRoot(List<AreaCodeGisVO> areaCodeList) {
		AreaCodeGisVO p = null;
		if(areaCodeList!=null && !areaCodeList.isEmpty()){
			for(AreaCodeGisVO areaCodeGisVO : areaCodeList) {
				if(StringUtils.isEmpty(areaCodeGisVO.getPcode())) {
					p = areaCodeGisVO;
					break;
				}
			}
			areaCodeList.remove(p);
			p.setChildren(areaCodeList);
		}
		
		return p;
	}
}
